<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

/**
* facebook账号登录二次封装
*/
class oauth2_facebook extends ms_oauth2
{
	public $name = 'facebook';
	
	private $client = null;
	private $openid = '';

	private $callback_url = 'api/auth_callback/facebook';

	function __construct()
	{
		parent::__construct();
		if(!class_exists('Facebook')) {
			require(MUDDER_ROOT.'api'.DS.'third_party'.DS.'src'.DS.'Facebook'.DS.'facebook.php');
		}

		$config = array(
			'appId' => S('member:passport_facebook_appid'),
			'secret' => S('member:passport_facebook_appsecret'),
			'allowSignedRequest' => false // optional but should be set to false for non-canvas apps
		);

		$this->client = new Facebook($config);
	}

	function getAuthorizeURL($callback_url = '')
	{
		$params = array(
		  'scope' => 'email,read_stream,friends_likes,publish_actions',
		  'redirect_uri' => $callback_url
		);

		$loginUrl = $this->client->getLoginUrl($params);
		return $loginUrl;
	}

	function getAccessToken($callback_url = '')
	{
		if (isset($_GET['code'])) {
			$access_token = $this->client->getAccessToken();
		}
		if(!$access_token) {
			log_write('oauth2_facebook', request_uri()."\nerror_code:"._T($_GET['error_code'])."\nerror_message:"._T($_GET['error_message'])."\n");
			if(DEBUG) {
				vp(_T($_GET['error_code']),_T($_GET['error_message']));
			}
			return;
		}
		$user_id = $this->client->getUser();
		if(!$user_id) {
			return;
		}

        $expires_in = _G('timestamp') + 5*365*3600*24;

		$newtoken = array (
			'name' 			=> $this->name, 
			'id'			=> $user_id,
			'access_token' 	=> $access_token, 
			'expires_in' 	=> $expires_in,		//授权剩余时间
		);
		return $this->_createToken($newtoken);
	}

	function getUserInfo($token = '')
	{
		$userinfo = array();
		try {

			$this->client->setAccessToken($token->setAccessToken);
			$user_id = $this->client->getUser();

			if($user_id > 0) {
				try {

					$user_profile = $this->client->api('/me','GET');

					$userinfo['passport_id'] = $user_id;
					$userinfo['username'] = $user_profile['name'];
					$userinfo['email'] = $user_profile['email'];

				} catch(FacebookApiException $e) {
					// If the user is logged out, you can have a 
					// user ID even though the access token is invalid.
					// In this case, we'll get an exception, so we'll
					// just ask the user to login again here.

					log_write('facebook', request_uri()."\n".$e->getType()."\n".$e->getMessage()."\n");
					if(DEBUG) {
						vp($e->getType(),$e->getMessage());
						//error_log($e->getType());
						//error_log($e->getMessage());
					}
				} 
			}

		} catch (Exception $e) {
			return $userinfo = array();
		}

	    if($userinfo && strtoupper(_G('charset')) != 'UTF-8') {
	        foreach($userinfo as $k => $v) {
	            if(is_string($v)) $userinfo[$k] = charset_convert($v,'utf-8',_G('charset'));
	        }
	    }

	    return $userinfo;
	}
}